// 简化的背景脚本 - 处理数据存储和转发
class SimpleInterceptor {
  constructor() {
    this.interceptedRequests = []; // 拦截规则数组
    this.requests = []; // 网络请求数组
    this.isEnabled = true;
    this.init();
  }

  async init() {
    // 从存储中加载数据
    await this.loadData();

    // 监听网络请求
    this.setupRequestListeners();

    // 监听来自popup的消息
    this.setupMessageListeners();

    // 监听扩展图标点击事件
    this.setupActionListener();
  }

  async loadData() {
    try {
      const result = await chrome.storage.local.get(['interceptedRequests', 'requests', 'isEnabled']);

      this.interceptedRequests = result.interceptedRequests || [];
      this.requests = result.requests || [];
      this.isEnabled = result.isEnabled !== false;
    } catch (error) {
      console.error('加载数据失败:', error);
    }
  }

  async saveData() {
    try {
      await chrome.storage.local.set({
        interceptedRequests: this.interceptedRequests,
        requests: this.requests,
        isEnabled: this.isEnabled
      });
    } catch (error) {
      console.error('保存数据失败:', error);
    }
  }

  setupRequestListeners() {
    // 监听所有网络请求，用于显示在popup中
    chrome.webRequest.onBeforeRequest.addListener(
      (details) => {
        // 过滤掉插件自身的请求和一些系统请求
        if (details.url.includes('chrome-extension://') ||
            details.url.includes('chrome://') ||
            details.url.includes('data:') ||
            details.url.includes('blob:')) {
          return;
        }

        // 通知popup有新请求
        this.notifyNewRequest({
          url: details.url,
          method: details.method,
          timestamp: Date.now()
        });
      },
      { urls: ['<all_urls>'] }
    );

    // 拦截响应，用于替换数据
    chrome.webRequest.onHeadersReceived.addListener(
      (details) => this.handleResponse(details),
      { urls: ['<all_urls>'] },
      ['responseHeaders']
    );
  }

  setupMessageListeners() {
    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
      this.handleMessage(message, sender, sendResponse);
      return true; // 保持消息通道开放
    });
  }

  notifyNewRequest(request) {
    // 通知所有popup窗口有新请求
    chrome.runtime.sendMessage({
      type: 'NEW_REQUEST',
      request: request
    }).catch(() => {
      // 忽略错误，popup可能没有打开
    });
  }

  handleResponse(details) {
    if (!this.isEnabled) return {};

    // 检查是否有拦截规则
    const responseData = this.interceptedRequests.get(details.url);
    if (!responseData) return {};

    console.log('拦截响应:', details.url);

    // 修改响应头，允许跨域和内容替换
    const headers = details.responseHeaders || [];

    // 移除可能阻止修改的头部
    const filteredHeaders = headers.filter(header => {
      const name = header.name.toLowerCase();
      return !['content-security-policy', 'x-frame-options'].includes(name);
    });

    // 添加允许跨域的头部
    filteredHeaders.push(
      { name: 'Access-Control-Allow-Origin', value: '*' },
      { name: 'Access-Control-Allow-Methods', value: '*' },
      { name: 'Access-Control-Allow-Headers', value: '*' }
    );

    return { responseHeaders: filteredHeaders };
  }

  async handleMessage(message, _sender, sendResponse) {
    try {
      switch (message.type) {
        case 'GET_DATA':
          sendResponse({
            intercepted: this.interceptedRequests,
            requests: this.requests,
            isEnabled: this.isEnabled
          });
          break;

        case 'SAVE_INTERCEPTED':
          this.interceptedRequests = message.data;
          await this.saveData();
          sendResponse({ success: true });
          break;

        case 'TOGGLE_ENABLED':
          this.isEnabled = message.enabled;
          await this.saveData();
          sendResponse({ success: true });
          break;

        case 'NEW_REQUEST':
          // 添加新请求到列表
          this.requests.unshift({
            id: Date.now() + Math.random(),
            ...message.request
          });

          // 只保留最近100个请求
          if (this.requests.length > 100) {
            this.requests = this.requests.slice(0, 100);
          }

          await this.saveData();
          sendResponse({ success: true });
          break;

        case 'CLEAR_REQUESTS':
          this.requests = [];
          await this.saveData();
          sendResponse({ success: true });
          break;

        default:
          sendResponse({ success: false, error: '未知消息类型' });
      }
    } catch (error) {
      console.error('处理消息错误:', error);
      sendResponse({ success: false, error: error.message });
    }
  }

  setupActionListener() {
    // 监听扩展图标点击事件
    chrome.action.onClicked.addListener(async (tab) => {
      try {
        // 切换启用状态
        this.isEnabled = !this.isEnabled;

        // 保存状态
        await chrome.storage.local.set({ isEnabled: this.isEnabled });

        // 更新图标和标题
        await this.updateActionIcon();

        // 通知所有content scripts更新状态
        chrome.tabs.query({}, (tabs) => {
          tabs.forEach(tab => {
            chrome.tabs.sendMessage(tab.id, {
              type: 'TOGGLE_EXTENSION',
              enabled: this.isEnabled
            }).catch(() => {
              // 忽略无法发送消息的标签页（如chrome://页面）
            });
          });
        });

        console.log(`Request Interceptor ${this.isEnabled ? '已启用' : '已禁用'}`);
      } catch (error) {
        console.error('切换扩展状态失败:', error);
      }
    });

    // 初始化图标状态
    this.updateActionIcon();
  }

  async updateActionIcon() {
    try {
      // 根据启用状态设置不同的图标和标题
      const iconPath = this.isEnabled ? {
        "16": "",
        "32": ""
      } : {
        "16": "",
        "32": ""
      };

      await chrome.action.setIcon({ path: iconPath });
      await chrome.action.setTitle({
        title: `Request Interceptor - ${this.isEnabled ? '已启用 (点击禁用)' : '已禁用 (点击启用)'}`
      });
    } catch (error) {
      console.error('更新图标失败:', error);
    }
  }
}

// 初始化简化拦截器
const interceptor = new SimpleInterceptor();
